package com.yyuap.nativeweb;

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.TextView;

import com.tencent.mm.sdk.platformtools.Log;
import com.yonyou.uap.um.application.ApplicationContext;
import com.yonyou.uap.um.base.UMEventArgs;
import com.yonyou.uap.um.common.StringFormat;
import com.yonyou.uap.um.control.UMTwoDCodeActivity;
import com.yonyou.uap.um.core.UMActivity;
import com.yonyou.uap.um.core.nativeweb.NWWindowActivity;
import com.yonyou.uap.um.core.nativeweb.NativeWebHelper;
import com.yonyou.uap.um.runtime.UMDevice;
import com.yonyou.uap.um.util.SimpleCallback;

public class MainActivity extends UMActivity implements View.OnTouchListener {
	protected static final String IP = "nw_ip";
	protected static final String NODE = "nw_node";
	private static final int OPEN_SETTING = 12322;
	protected static final String PORT = "nw_port";
	private long lastTime = 0L;
	private View.OnClickListener startNativeWebPage = new View.OnClickListener() {
		public void onClick(View paramAnonymousView) {
			MainActivity.this.openPlay();
		}
	};
	private TextView status = null;

	private static boolean deleteDir(File paramFile) {
		if (paramFile.isDirectory()) {
            paramFile.delete();
		}

		return false;
	}

	private static void deleteFilesByDirectory(File paramFile) {
		if ((paramFile != null) && (paramFile.exists())
				&& (paramFile.isDirectory())) {
			File[] paramFiles = paramFile.listFiles();
			for (int k = 0; k < paramFiles.length; k++) {
				deleteDir(paramFiles[k]);
			}
		}
	}

	private String getCurrentAddress(UMActivity paramUMActivity) {
		SharedPreferences s = paramUMActivity.getSharedPreferences(
				"umservice_configure", 0);
		String str = s.getString("nwip", "");
		if (TextUtils.isEmpty(str))
			return "";
		return StringFormat.format("http://{0}:{1}/",
				new Object[] { str, s.getString("nwport", "8888") });
	}

	private void getOverflowMenu() {
		try {
			ViewConfiguration localViewConfiguration = ViewConfiguration
					.get(this);
			Field localField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			if (localField != null) {
				localField.setAccessible(true);
				localField.setBoolean(localViewConfiguration, false);
			}
			return;
		} catch (Exception localException) {
			localException.printStackTrace();
		}
	}

	private void initNativeWeb() {
		ApplicationContext.getCurrent(this);
		refreshAddressStatus();
		findViewById(R.id.btnSetting).setOnTouchListener(this);
		findViewById(R.id.btnGo).setOnTouchListener(this);
		findViewById(R.id.btnClear).setOnTouchListener(this);
		try {
			PackageInfo localPackageInfo = getPackageManager().getPackageInfo(
					getPackageName(), 0);
			((TextView) findViewById(R.id.txtVersion)).setText("VER : "
					+ localPackageInfo.versionName);
			return;
		} catch (PackageManager.NameNotFoundException localNameNotFoundException) {
			localNameNotFoundException.printStackTrace();
		}
	}

	private void loadURLBySetting(UMActivity paramUMActivity) {
		NativeWebHelper.get(StringFormat.format("{0}adrurl",
				new Object[] { getCurrentAddress(paramUMActivity) }),
				new SimpleCallback() {
					public void callback(int paramAnonymousInt,
							Object paramAnonymousObject) {
						if (paramAnonymousInt != 1) {
							MainActivity.this.writeStatus("服务器连接异常\n\r"
									+ paramAnonymousObject);
							return;
						}
						MainActivity.this.openPlay(paramAnonymousObject
								.toString());
					}
				}, false);
	}

	private void openClear() {
		writeStatus("开始清除...");
		NativeWebHelper.clearProject();
		deleteFilesByDirectory(getFilesDir());
		writeStatus("清除缓存完成!");
	}

	private void openPlay() {
		String str = getCurrentAddress(this);
		if (TextUtils.isEmpty(str)) {
			showMessage("消息", "未设置服务器地址.");
			return;
		}
		writeStatus("准备打开...\n\r" + str);
		NativeWebHelper.clearDrawableResource(this);
		loadURLBySetting(this);
	}

	private void openPlay(String paramString) {
		NativeWebHelper.clearDrawableResource(this);
		writeStatus("连接成功，准备打开\n\r" + paramString);
		NWWindowActivity.openPage(this, paramString, null);
	}

	private void openSetting() {
		startActivityForResult(new Intent(this, SettingActivity.class), 12322);
	}

	private void refreshAddressStatus() {
		String str = getCurrentAddress(this);
		if (TextUtils.isEmpty(str)) {
			writeStatus("未配置服务器地址，请设置");
			return;
		}
		writeStatus("当前服务器地址\n\r" + str);
	}

	private void writeStatus(String paramString) {
		if (this.status == null)
			this.status = ((TextView) findViewById(R.id.txtStatus));
		paramString = StringFormat.format(
				"{0}\n\r[{1}]",
				new Object[] {
						paramString,
						new SimpleDateFormat("MM-dd hh:mm:ss").format(
								new Date(System.currentTimeMillis()))
								.toString() });
		this.status.setText(paramString);
	}

	public String getContextName() {
		return null;
	}

	public String getControllerName() {
		return null;
	}

	public String getNameSpace() {
		return null;
	}

	protected void onActivityResult(int paramInt1, int paramInt2,
			Intent paramIntent) {

		if (paramInt2 != paramInt1) {
			refreshAddressStatus();
		}
		UMDevice.vibrator(UMEventArgs.obtain(this));
		String code = getCurrentAddress(this);
		if (!code.startsWith("http")) {
			writeStatus("无效的URL地址\n\r" + paramIntent);
			return;
		}
		openPlay(code);
	}

	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.main);
		initNativeWeb();
		getOverflowMenu();
	}

	public boolean onCreateOptionsMenu(Menu paramMenu) {
		getMenuInflater().inflate(R.menu.menu, paramMenu);
		return super.onCreateOptionsMenu(paramMenu);
	}

	public void onInit(Bundle paramBundle) {
	}

	public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {
		if ((paramInt == 4) && (paramKeyEvent.getAction() == 0)) {
			if (System.currentTimeMillis() - this.lastTime > 2000L) {
				writeStatus("请再按一次返回键退出程序");
				this.lastTime = System.currentTimeMillis();
			}
			finish();
		}
		return super.onKeyDown(paramInt, paramKeyEvent);
	}

	public boolean onOptionsItemSelected(MenuItem paramMenuItem) {
		switch (paramMenuItem.getItemId()) {
		default:
		case R.id.btnGo:
			openPlay();
		case R.id.btnSetting:
			openSetting();
		case R.id.btnClear:
			openClear();
		case 2131361860:
			finish();
		}

		return super.onOptionsItemSelected(paramMenuItem);

	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint({ "ClickableViewAccessibility", "NewApi" })
	public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
        switch (paramMotionEvent.getAction()){

        }
			if (paramView.getId() == R.id.btnGo)
				openPlay();
			if (paramView.getId() == R.id.btnSetting)
				openSetting();
			if (paramView.getId() == R.id.btnClear)
				openClear();

		return true;
	}
}
